<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\Plugin\ContactTodo\Action\Sidebar;

use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\Utils\Codec\Json;
use MoChat\App\Common\Middleware\SidebarAuthMiddleware;
use MoChat\App\WorkContact\Contract\WorkContactContract;
use MoChat\App\WorkEmployee\Contract\WorkEmployeeContract;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;
use MoChat\Framework\Request\ValidateSceneTrait;
use MoChat\Plugin\ContactTodo\Contract\ContactTodoContract;
use MoChat\Plugin\ContactTrack\Constants\Event;
use MoChat\Plugin\ContactTrack\Constants\EventName;
use MoChat\Plugin\ContactTrack\Contract\ContactTrackContract;

/**
 * 添加待办.
 *
 * Class Store
 * @Controller
 */
class Store extends AbstractAction
{
    use ValidateSceneTrait;

    /**
     * @Inject
     * @var WorkContactContract
     */
    protected $workContact;

    /**
     * @Inject
     * @var ContactTodoContract
     */
    protected $contactTodoService;

    /**
     * @Inject
     * @var WorkEmployeeContract
     */
    protected $workEmployee;

    /**
     * @Inject
     * @var StdoutLoggerInterface
     */
    protected $logger;

    /**
     * 互动轨迹表.
     * @Inject
     * @var ContactTrackContract
     */
    private $track;

    /**
     * @Middlewares({
     *     @Middleware(SidebarAuthMiddleware::class)
     * })
     * @RequestMapping(path="/sidebar/contactTodo/store", methods="POST")
     */
    public function handle(): array
    {
        // 接收参数
        $params = [
            'type' => (int) $this->request->input('type'),
            'contactId' => (int) $this->request->input('contactId'),
            'timingRemind' => $this->request->input('timingRemind', []),
            'cycleRemind' => $this->request->input('cycleRemind', []),
        ];
        // 校验参数
        $this->validated($params);

        $employee = $this->workEmployee->getWorkEmployeeById((int) user()['id'], ['wx_user_id']);
        $contact = $this->workContact->getWorkContactById((int) $params['contactId'], ['wx_external_userid']);
        // 数据操作
        Db::beginTransaction();
        try {
            // 定时提醒
            if ($params['type'] === 1) {
                if (empty($params['timingRemind'])) {
                    throw new CommonException(ErrorCode::INVALID_PARAMS, '定时提醒为空，不可操作');
                }
                foreach ($params['timingRemind'] as $item) {
                    $data = [
                        'type' => $params['type'],
                        'corp_id' => user()['corpId'],
                        'employee_id' => user()['id'],
                        'contact_id' => $params['contactId'],
                        'content' => $item['content'],
                        'wx_user_id' => $employee['wxUserId'],
                        'wx_external_userid' => $contact['wxExternalUserid'],
                        'day' => $item['day'],
                        'time' => $item['time'],
                        'created_at' => date('Y-m-d H:i:s'),
                    ];
                    // 添加待办
                    $id = $this->contactTodoService->createContactTodo($data);
                    // 记录轨迹
                    $this->recordTrack($params['contactId'], $item['content'], $id);
                }
            }
            // 周期提醒
            if ($params['type'] === 2) {
                if (empty($params['cycleRemind'])) {
                    throw new CommonException(ErrorCode::INVALID_PARAMS, '周期提醒为空，不可操作');
                }
                $data = [
                    'type' => $params['type'],
                    'corp_id' => user()['corpId'],
                    'employee_id' => user()['id'],
                    'contact_id' => $params['contactId'],
                    'content' => $params['cycleRemind']['content'],
                    'wx_user_id' => $employee['wxUserId'],
                    'wx_external_userid' => $contact['wxExternalUserid'],
                    'day' => $params['cycleRemind']['day'],
                    'time' => $params['cycleRemind']['time'],
                    'repeat' => empty($params['cycleRemind']['repeat']) ? '{}' : Json::encode($params['cycleRemind']['repeat']),
                    'end_repeat' => empty($params['cycleRemind']['endRepeat']) ? '{}' : Json::encode($params['cycleRemind']['endRepeat']),
                    'created_at' => date('Y-m-d H:i:s'),
                ];
                // 添加待办
                $id = $this->contactTodoService->createContactTodo($data);
                // 记录轨迹
                $this->recordTrack($params['contactId'], $params['cycleRemind']['content'], $id);
            }

            Db::commit();
            return [];
        } catch (\Throwable $e) {
            Db::rollBack();
            $this->logger->error(sprintf('%s [%s] %s', '添加待办失败', date('Y-m-d H:i:s'), $e->getMessage()));
            $this->logger->error($e->getTraceAsString());
            throw new CommonException(ErrorCode::SERVER_ERROR, $e->getMessage()); // '活动创建失败'
        }
    }

    /**
     * @return string[] 规则
     */
    public function rules(): array
    {
        return [
            'type' => 'required',
            'contactId' => 'required|integer|min:1|bail',
        ];
    }

    /**
     * 获取已定义验证规则的错误消息.
     */
    public function messages(): array
    {
        return [
            'type.required' => '类型 必传',
            'contactId.required' => '客户id必传',
        ];
    }

    /**
     * 记录轨迹.
     * @param $contactId
     * @param $content
     * @param $id
     */
    private function recordTrack($contactId, $content, $id)
    {
        $jsonContact = [
            'title' => EventName::TODO,
            'content' => $content,
            'target_id' => $id,
        ];
        $data = [
            'employee_id' => user()['id'],
            'contact_id' => $contactId,
            'content' => Json::encode($jsonContact),
            'corp_id' => user()['corpId'],
            'event' => Event::TODO,
        ];

        $res = $this->track->createContactTrack($data);
        if (! is_int($res)) {
            throw new CommonException(ErrorCode::SERVER_ERROR, '记录轨迹失败');
        }
    }
}
